package cn.maihe.elg.operation.supports.electronicseal.anne.bean.annesign.base;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import cn.maihe.elg.operation.supports.electronicseal.anne.utils.annesign.AnneSignConst;
import cn.maihe.elg.operation.supports.electronicseal.anne.utils.annesign.ValidateException;
import cn.maihe.elg.operation.supports.electronicseal.anne.utils.annesign.ValidateUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;

public class SecureApiResponse extends BaseApiResponse {

    private String sign;

    public SecureApiResponse() {
    }

    @Override
    public boolean validate() throws ValidateException {
        try {
            return ValidateUtils.validate(this);
        } catch (ValidateException e) {
            throw new ValidateException(e.getMessage(), e);
        }
    }

    /**
     * 获取签名
     *
     * @param secretKey
     * @return
     */
    @JsonIgnore
    public String getSign(String secretKey) {
        StringBuilder sb = new StringBuilder();
        sb.append(this.code);
        sb.append(this.timestamp);
        sb.append(this.uuid);
        sb.append(this.version);
        HMac hMac = SecureUtil.hmac(HmacAlgorithm.HmacSHA256, secretKey);
        return hMac.digestHex(sb.toString());
        //return new HmacUtils(HmacAlgorithms.HMAC_SHA_256, secretKey).hmacHex(sb.toString());
    }

    /**
     * 响应及签名是否都正确（抛异常，请使用带签名的方法）
     *
     * @return
     */
    @JsonIgnore
    public Boolean isOk() {
        throw new UnsupportedOperationException("不支持的操作，请使用isOk(secretKey)");
    }

    @JsonIgnore
    public String respMsg() {
        return String.format("[%s:%s]", this.getCode(), this.getDetail());
    }

    /**
     * 响应及签名是否都正确
     *
     * @return
     */
    @JsonIgnore
    public Boolean isOk(String secretKey) {
        return AnneSignConst.RESPONSE_OK_CODE.equals(this.code) && this.getSign(secretKey).equals(this.sign);
    }

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }
}
